<?php

namespace App\Model\Manage;

use Illuminate\Database\Eloquent\Model;

class ManageRoleMapAction extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'manage_role_map_action';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     *
     * 更新角色与权限关联关系
     *
     * @param $role
     * @param $action
     * @return bool
     */
    public static function updateMap($role, $action)
    {
        # 查询角色拥有的关联权限
        $map = self::getMap($role);
        # 循环数组操作
        $deleteID = array();
        $insertData = array();
        # 清空全部关联记录
        if (empty($action)) {
            self::where('role_id', $role)->delete();
            return true;
        }
        # 分组比对修改数据与原始数据
        foreach ($action as $key => $val) {
            # 对比原始数据与修改数据之间差值，差值为需要删除的关联数据
            if (isset($map[$key])) {
                $del = array_diff($map[$key], $val);
                $deleteID = array_merge($deleteID, $del);
            }
            # 对比修改数据与原始数据之间的差值，差值为需要新增的关联数据，如果没有原始数据需要新增全部修改数据
            $add = isset($map[$key]) ? array_diff($val, $map[$key]) : $val;
            foreach ($add as $v) {
                $insertData[] = [
                    'action_parent_id' => $key,
                    'role_id' => $role,
                    'action_id' => $v,
                    'create_time' => date('Y-m-d H:i:s', time()),
                ];
            }
            # 清除已比对过的原始数据变量
            unset($map[$key]);
        }
        # 如果原始数据变量依然有分组值存在，则需要清除整组数据
        foreach ($map as $val) {
            if (!empty($val)) {
                $deleteID = array_merge($deleteID, $val);
            }
        }
        if ($insertData) self::insert($insertData);
        if ($deleteID) self::where('role_id', $role)->whereIn('action_id', $deleteID)->delete();
    }

    public static function getMap($role)
    {
        $data = [];
        $result = self::where('role_id', $role)->get();
        foreach ($result as $value) {
            $data[$value->action_parent_id][] = $value->action_id;
        }
        return $data;
    }
}